<template>
  <div>
    <!-- 搜索 & 新增管理员 -->
    <el-input
        v-model="filters.name"
        placeholder="按姓名搜索"
        clearable
        @clear="fetchAdmins"
        @keyup.enter="fetchAdmins"
        style="width: 240px; margin-bottom: 16px"
    >
      <template #append>
        <el-button @click="fetchAdmins">
          <el-icon><Search /></el-icon>
        </el-button>
      </template>
    </el-input>
    <el-button type="primary" @click="openCreateDialog" style="margin-bottom: 16px">
      新增管理员
    </el-button>

    <!-- 管理员表格 -->
    <el-table
        :data="admins"
        v-if="admins.length"
        border
        stripe
        style="width: 100%; margin-top: 16px"
    >
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="adAccount" label="账号" />
      <el-table-column prop="adName" label="姓名" />
      <el-table-column prop="phone" label="电话" />
      <el-table-column prop="role" label="角色" />
      <el-table-column label="服务对象">
        <template #default="{ row }">
          <el-button
              v-if="row.role === '健康管家'"
              size="small"
              type="primary"
              @click="openClientsDialog(row.adId)"
          >查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button size="small" @click="toEdit(row.adId)">编辑</el-button>
          <el-button size="small" type="danger" @click="onDelete(row.adId)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-else class="empty">暂无数据</div>

    <!-- 管理员列表分页 -->
    <div class="pagination-container" style="margin-top: 20px; display: flex; justify-content: flex-end;">
      <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="adminPagination.total"
          v-model:current-page="adminPagination.current"
          v-model:page-size="adminPagination.size"
          :page-sizes="[6, 10, 20, 50]"
          @current-change="handleAdminPageChange"
          @size-change="handleAdminSizeChange"
      />
    </div>

    <!-- 新增/编辑管理员 Dialog -->
    <el-dialog
        :title="isEditing ? '编辑管理员' : '新增管理员'"
        v-model="showEditDialog"
        width="480px"
        @close="resetForm"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="账号">
          <el-input v-model="form.adAccount" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="form.adName" />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="form.phone" @blur="syncPasswordFromPhone" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option label="健康管家" value="健康管家" />
            <el-option label="管理员" value="管理员" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">
          {{ isEditing ? '保存' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 服务对象列表 Dialog -->
    <el-dialog
        title="服务对象列表"
        v-model="showClientsDialog"
        width="700px"
        @close="resetClientsPagination"
    >
      <el-table
          :data="clients"
          border
          stripe
          @selection-change="onUnassignSelectionChange"
          ref="clientsTable"
      >
        <!-- 多选列 -->
        <el-table-column type="selection" width="55" />
        <!-- 原来的列保持不变 -->
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="clientName" label="姓名" />
        <el-table-column prop="clientPhone" label="电话" />
        <el-table-column prop="clientType" label="类型" />
        <!-- 可以把原来的“操作”列删掉或保留单个按钮备用 -->
      </el-table>

      <div style="text-align: right; margin-top: 12px;">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="clientPagination.total"
            v-model:current-page="clientPagination.current"
            v-model:page-size="clientPagination.size"
            :page-sizes="[5, 10, 20]"
            @current-change="handleClientPageChange"
            @size-change="handleClientSizeChange"
        />
      </div>
      <div class="dialog-footer" style="text-align: right; margin-top: 12px;">
        <el-button @click="showClientsDialog = false">关闭</el-button>
        <el-button
            type="danger"
            :disabled="!selectedUnassignIds.length"
            @click="confirmUnassign"
        >移除</el-button>
        <el-button type="primary" @click="openAssignDialog">
          增加服务对象
        </el-button>
      </div>
    </el-dialog>

    <!-- 添加服务对象 Dialog -->
    <el-dialog
        title="添加服务对象"
        v-model="showAssignDialog"
        width="600px"
        @close="resetAssignPagination"
    >
      <el-input
          v-model="assignFilters.name"
          placeholder="按姓名搜索"
          clearable
          @clear="fetchUnassigned"
          @keyup.enter="fetchUnassigned"
          style="width: 240px; margin-bottom: 12px"
      >
        <template #append>
          <el-button @click="fetchUnassigned">搜索</el-button>
        </template>
      </el-input>
      <el-table
          :data="unassignedClients"
          border
          stripe
          @selection-change="onSelectionChange"
          ref="assignTable"
      >
        <!-- 多选列 -->
        <el-table-column type="selection" width="55" />
        <!-- 其他列保持不变 -->
        <el-table-column prop="clientName" label="姓名" />
        <el-table-column prop="clientPhone" label="电话" />
        <el-table-column prop="clientType" label="类型" />
      </el-table>
      <div style="text-align: right; margin-top: 12px;">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="assignPagination.total"
            v-model:current-page="assignPagination.current"
            v-model:page-size="assignPagination.size"
            :page-sizes="[5, 10, 20]"
            @current-change="handleAssignPageChange"
            @size-change="handleAssignSizeChange"
        />
      </div>
      <div class="dialog-footer" style="text-align: right; margin-top: 12px;">
        <el-button @click="showAssignDialog = false">取消</el-button>
        <el-button
            type="primary"
            :disabled="!selectedClientIds.length"
            @click="confirmAssign"
        >确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import {
  listCareAdmins,
  createAdmin,
  updateAdmin,
  unassignClient,
  deleteAdmin,
  listClientsByAdmin
} from '@/api/apiList/admin'
import {
  listUnassignedCareClients,
  assignClientToAdmin
} from '@/api/apiList/client'

// 管理员列表 & 分页
const admins = ref([])
const filters = reactive({ name: '' })
const adminPagination = reactive({ current: 1, size: 10, total: 0 })

async function fetchAdmins() {
  try {
    const data = await listCareAdmins(filters.name, adminPagination.current, adminPagination.size)
    admins.value = data.records
    adminPagination.total = data.total
  } catch {
    ElMessage.error('获取管理员列表失败')
  }
}
function handleAdminPageChange(p) {
  adminPagination.current = p; fetchAdmins()
}
function handleAdminSizeChange(s) {
  adminPagination.size = s; adminPagination.current = 1; fetchAdmins()
}

// 创建/编辑管理员
const showEditDialog = ref(false)
const isEditing = ref(false)
const form = reactive({
  adId: null,
  adAccount: '',
  adPassword: '',
  adName: '',
  phone: '',
  role: ''
})
// 多选时保存所有选中的 clientId
const selectedClientIds = ref([])

function onSelectionChange(selection) {
  selectedClientIds.value = selection.map(item => item.clientId)
}
const selectedUnassignIds = ref([])

function onUnassignSelectionChange(selection) {
  selectedUnassignIds.value = selection.map(item => item.clientId)
}

function openCreateDialog() {
  isEditing.value = false; resetForm(); showEditDialog.value = true
}
async function toEdit(id) {
  isEditing.value = true
  const page = await listCareAdmins(filters.name, adminPagination.current, adminPagination.size)
  const admin = page.records.find(a => a.adId === id)
  if (admin) {
    Object.assign(form, admin)
    showEditDialog.value = true
  } else {
    ElMessage.error('未找到该管理员')
  }
}
function resetForm() {
  form.adId = null; form.adAccount = ''; form.adPassword = ''
  form.adName = ''; form.phone = ''; form.role = ''
}
async function submitForm() {
  try {
    if (isEditing.value) await updateAdmin(form), ElMessage.success('更新成功')
    else await createAdmin(form), ElMessage.success('创建成功')
    showEditDialog.value = false; fetchAdmins()
  } catch {
    ElMessage.error((isEditing.value ? '更新' : '创建') + '失败')
  }
}
function syncPasswordFromPhone() {
  if (!isEditing.value && form.phone?.length >= 6) {
    form.adPassword = form.phone.slice(-6)
  }
}
async function onDelete(id) {
  try {
    await ElMessageBox.confirm('确认删除？', '提示', { type: 'warning' })
    await deleteAdmin(id)
    ElMessage.success('删除成功')
    fetchAdmins()
  } catch {}
}

// 服务对象列表 & 分页
const showClientsDialog = ref(false)
const currentAdminId = ref(null)
const clients = ref([])
const assignTable = ref(null)
const clientPagination = reactive({ current: 1, size: 10, total: 0 })
async function openClientsDialog(adminId) {
  currentAdminId.value = adminId
  clientPagination.current = 1
  await fetchClients()
  showClientsDialog.value = true
}
async function fetchClients() {
  try {
    const data = await listClientsByAdmin(
        currentAdminId.value,
        clientPagination.current,
        clientPagination.size
    )
    clients.value = data.records
    clientPagination.total = data.total
  } catch {
    ElMessage.error('获取服务对象失败')
  }
}
function handleClientPageChange(p) {
  clientPagination.current = p; fetchClients()
}
function handleClientSizeChange(s) {
  clientPagination.size = s; clientPagination.current = 1; fetchClients()
}
async function confirmUnassign() {
  if (!selectedUnassignIds.value.length) return
  try {
    await ElMessageBox.confirm(
        `确认移除 ${selectedUnassignIds.value.length} 个服务对象？`,
        '提示',
        { type: 'warning' }
    )
    // 如果后端支持批量接口，直接调用；否则遍历调用
    await Promise.all(
        selectedUnassignIds.value.map(id =>
            unassignClient(id)
        )
    )
    ElMessage.success('移除成功')
    // 刷新列表
    fetchClients()
    // 清空选中
    selectedUnassignIds.value = []
    refs.clientsTable.clearSelection()
  } catch {
    // 用户取消或错误
  }
}

function resetClientsPagination() {
  clientPagination.current = 1; clientPagination.size = 10
  clientPagination.total = 0; clients.value = []
}

// 添加服务对象列表 & 分页
const showAssignDialog = ref(false)
const assignFilters = reactive({ name: '' })
const unassignedClients = ref([])
const assignPagination = reactive({ current: 1, size: 10, total: 0 })
const selectedClientId = ref(null)
function openAssignDialog() {
  assignFilters.name = ''; selectedClientId.value = null
  assignPagination.current = 1; fetchUnassigned()
  showAssignDialog.value = true
}
async function fetchUnassigned() {
  try {
    const data = await listUnassignedCareClients(
        assignFilters.name,
        assignPagination.current,
        assignPagination.size
    )
    unassignedClients.value = data.records
    assignPagination.total = data.total
  } catch {
    ElMessage.error('获取候选客户失败')
  }
}
function handleAssignPageChange(p) {
  assignPagination.current = p; fetchUnassigned()
}
function handleAssignSizeChange(s) {
  assignPagination.size = s; assignPagination.current = 1; fetchUnassigned()
}
function onSelectUnassigned(row) {
  selectedClientId.value = row.clientId
}
async function confirmAssign() {
  if (!selectedClientIds.value.length) return
  try {
    // 只包裹网络请求
    await Promise.all(
        selectedClientIds.value.map(id =>
            assignClientToAdmin(id, currentAdminId.value)
        )
    )
    ElMessage.success('添加成功')
  } catch (e) {
    // 只有当真正的请求失败才走这里
    return ElMessage.error('添加失败')
  }

  // 下面这部分放在 try 外，避免一处小错误也走到上面的 catch
  fetchClients()
  fetchUnassigned()
  selectedClientIds.value = []

  // clearSelection 也要做空值校验
  if (assignTable.value) {
    assignTable.value.clearSelection()
  }
  showAssignDialog.value = false
}

function resetAssignPagination() {
  assignPagination.current = 1; assignPagination.size = 10
  assignPagination.total = 0; unassignedClients.value = []; selectedClientId.value = null
}

onMounted(fetchAdmins)
</script>

<style scoped>
.empty {
  text-align: center;
  margin: 40px 0;
  color: #888;
}
</style>
